<template>
  <div class="filter-container">
    <Category
      title="资源下载"
      placeholder="请输入资源名称"
      @onSearch="seacrh"
      :filterOptions="filterOptions"
      :category="category"
      @updateSelected="updateSelected"
    />
    <ThumbnailList
      :tableConfig="tableConfig"
      @sizeChange="sizeChangeBtn"
      @currentChange="handleCurrentChangeBtn"
      @sortBy="sortBySearch"
      @sortList="sortList"
      @actionDialog="actionDialog"
      @downFile="downFile"
    />
  </div>
  <Dialog
    style="max-height: none"
    v-model:showDialog="show"
    @close="close"
    :detailData="detailData"
    @downFile="downFile"
  ></Dialog>
</template>

<script setup>
import { useRoute } from 'vue-router';
const route = useRoute();
import { reactive, onMounted } from 'vue';
// 顶部筛选组件
import Category from '@/components/Category/index.vue';
// 底部缩略图+列表组件
import ThumbnailList from '@/views/serviceCenter/components/thumbnail/index.vue';
//弹窗
import Dialog from './components/dialog.vue';
// 下载资源文件/图片   判断是否为压缩格式
import { downloadImage, isCompressedFile } from '@/utils';
import {
  getCategoryList,
  getManagerResource,
  addDownloadNum,
  managerResourceInfo,
} from '@/api/serviceCenter';

const category = ref({
  pid: route.query.parentId || '',
  id: route.query.id || '',
});
// 弹窗详情数据
const detailData = reactive({});
// 筛选
const filterOptions = ref([]);
// 顶部筛选
const updateSelected = (ids) => {
  tableConfig.page = 1;
  tableConfig.search_id = ids;
  tableList();
};
// 表格数据
const tableConfig = reactive({
  // 总数据量
  total: 0,
  // 当前页码
  page: 1,
  // 每页显示的数据条数
  pageSize: 30,
  // 表格数据
  list: [],
  //搜索
  search: '',
  // 搜索排序类型 1.desc 2.asc
  sortType: '',
  sort: '',
  // 表格表头
  columns: [
    { label: '封面', prop: 'cover_img', type: 'image', width: '218' },
    { label: '资源名称', prop: 'name', width: '296', type: 'name' },
    { label: '所属分类', prop: 'className', width: '270' },
    {
      label: '文件格式',
      prop: 'fileType',
      width: '270',
    },
    { label: '文件大小', prop: 'fileSize', sortable: true, width: '150' },
    { label: '热度', prop: 'sort', sortable: true, width: '150' },
    { label: '上架时间', prop: 'create_time', sortable: true, width: '200' },
    {
      label: '操作',
      type: 'actions',
      fixed: 'right',
      width: '140',
      actions: [{ type: 'down', label: '下载', pageType: 'resourceDownload' }],
    },
  ],
});
// 请求表格列表数据
const tableList = async () => {
  const requestData = JSON.parse(JSON.stringify(tableConfig));
  // 删除不需要的字段
  delete requestData.columns;
  delete requestData.list;
  delete requestData.total;
  try {
    const { data } = await getManagerResource(requestData);

    tableConfig.total = data.total;
    tableConfig.list = data.data;
  } catch (error) {
    console.log('error:', error);
  }
};
const show = ref(false);
// 点击图层弹窗
const actionDialog = async (val) => {
  console.log('55555555555');
  if (val.fileType == 'pdf') return window.open(val.file, '_blank');
  const isComp = isCompressedFile(val.file);
  if (isComp) return downFile(val);
  const { data } = await managerResourceInfo({ id: val.id });
  Object.assign(detailData, data);
  show.value = true;
};
const close = () => {
  show.value = false;
};
//处理页码切换
const sizeChangeBtn = (val) => {
  tableConfig.page = val;
  tableList();
};
//处理页码切换
const handleCurrentChangeBtn = (val) => {
  tableConfig.page = val;
  tableList();
};
// 请求顶部筛选数据
const categoryList = async () => {
  try {
    const { data } = await getCategoryList({ type: 2 });
    data.forEach((group) => {
      if (Array.isArray(group.childs)) {
        group.childs.unshift({
          name: '不限',
          id: 'all',
        });
      }
    });
    filterOptions.value = data;
  } catch (error) {
    console.log('error:', error);
  }
};
// 搜索
const seacrh = (val) => {
  tableConfig.search = val;
  tableList();
};
//上架时间和下载时间
const sortBySearch = (val, fag) => {
  tableConfig.sortType = fag == '上架时间' ? 2 : 1;
  tableConfig.sort = val;
  tableList();
};

// 定义排序优先级映射
const sortPriorityMap = {
  sort: 1, // 热度排序优先级 1
  create_time: 2, // 时间排序优先级 2
  fileSize: 3, // 文件大小排序优先级 3
  fileType: 4, // 文件大小排序优先级 4
};
// 封装函数，根据字段名称获取排序优先级
const getSortPriority = (prop) => {
  return sortPriorityMap[prop] || 1; // 默认优先级为 999（最小优先级）
};

//列表排序
const sortList = ({ prop, order }) => {
  const sortOrder = order === 'ascending' ? 'asc' : 'desc';
  // 更新排序字段和顺序
  tableConfig.sort = sortOrder;
  tableConfig.sortType = getSortPriority(prop);
  // 调用方法向服务器请求排序后的数据
  tableList();
};
// 资源下载文件
const downFile = async (row) => {
  try {
    await downloadImage(row.file, row.name); // 等待下载完成
    await addDownloadNum({ type: 2, id: row.id }); // 下载完成后增加下载次数
  } catch (error) {
    console.log('error:', error);
  }
};
onMounted(() => {
  // 顶部筛选分类
  categoryList();

  if (route.query.ids) {
    updateSelected(route.query.ids);
  } else {
    // 底部表格
    tableList();
  }
});
</script>

<style scoped lang="scss">
:deep(.el-dialog__body) {
  overflow-y: unset !important;
  overflow: unset !important;
}
.filter-container {
  margin: 30px 40px;
  display: flex;
  flex-direction: column;
  gap: 30px;
}
</style>
